package com.ihelin.insurance.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ihelin.insurance.entity.*;
import com.ihelin.insurance.service.*;
import com.ihelin.insurance.utils.R;
import com.ihelin.insurance.utils.SystemUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author iHelin
 * @since 2021/2/27 14:18
 */
@RestController
public class AdminController {

    @Autowired
    private AdminService adminService;
    @Autowired
    private AgentService agentService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private PerformanceService performanceService;
    @Autowired
    private PaymentService paymentService;

    /**
     * 登录
     *
     * @param adminUser
     * @param session
     * @return
     */
    @PostMapping("/admin/login")
    public R login(@RequestBody AdminUser adminUser, HttpSession session) {
        String username = adminUser.getUsername();
        AdminUser adminUserFromDB = adminService.loadUserByUsername(username);
        if (adminUserFromDB != null && adminUserFromDB.getPassword().equals(adminUser.getPassword())) {
            session.setAttribute("adminUser", adminUserFromDB);
            return R.ok();
        }
        return R.error("用户名或密码错误！");
    }

    /**
     * 代理人信息
     */
    @GetMapping("/admin/agents/info/{id}")
    public R agentInfo(@PathVariable("id") Integer id) {
        AgentEntity agentEntity = agentService.getById(id);
        return R.ok().put("data", agentEntity);
    }

    /**
     * 代理人列表
     */
    @GetMapping("/admin/agents/list")
    public R agentList(Long page, Long limit, String key) {
        QueryWrapper<AgentEntity> queryWrapper = new QueryWrapper<>();
        if (StringUtils.hasText(key)) {
            queryWrapper.eq("id", key);
        }
        IPage<AgentEntity> agentPage = agentService.page(new Page<>(page, limit), queryWrapper);
        return R.ok(agentPage);
    }

    /**
     * 新增代理人
     */
    @PostMapping("/admin/agents/save")
    public R saveAgent(@RequestBody AgentEntity agentEntity) {
        agentEntity.setUsername(UUID.randomUUID().toString().replace("-", "").substring(0, 6));
        agentEntity.setPassword("123456");
        agentService.save(agentEntity);
        return R.ok();
    }

    /**
     * 修改代理人
     */
    @PutMapping("/admin/agents/update")
    public R updateAgent(@RequestBody AgentEntity agentEntity) {
        agentService.updateAgent(agentEntity);
        return R.ok();
    }

    /**
     * 删除代理人
     */
    @DeleteMapping("/admin/agents/delete")
    public R deleteAgent(@RequestBody List<Integer> ids) {
        agentService.deleteAgent(ids);
        return R.ok();
    }

    /**
     * customers列表
     */
    @GetMapping("/admin/customers/list")
    public R customers(Long page, Long limit, String key) {
        QueryWrapper<CustomerEntity> queryWrapper = new QueryWrapper<>();
        if (StringUtils.hasText(key)) {
            queryWrapper.eq("id", key);
        }
        IPage<CustomerEntity> data = customerService.page(new Page<>(page, limit), queryWrapper);
        return R.ok(data);
    }

    /**
     * 绩效列表
     */
    @GetMapping("/admin/performance/list")
    public R performances(Long page, Long limit, String key) {
        QueryWrapper<PerformanceEntity> queryWrapper = new QueryWrapper<>();
        if (StringUtils.hasText(key)) {
            queryWrapper.eq("agent_id", key);
        }
        IPage<PerformanceEntity> data = performanceService.page(new Page<>(page, limit), queryWrapper);
        return R.ok(data);
    }

    /**
     * 计算绩效
     *
     * @return
     */
    @GetMapping("/admin/performance/cal")
    public R calPerformance() {
        agentService.calPerformance();
        return R.ok();
    }


    @PostMapping("/admin/performance/days")
    public R editDays(@RequestBody PerformanceEntity performanceEntity) {
        performanceService.updateById(performanceEntity);
        return R.ok();
    }

    @GetMapping("/admin/payment/list")
    public R payments(Long page, Long limit, String key) {
        QueryWrapper<PaymentEntity> queryWrapper = new QueryWrapper<>();
        if (StringUtils.hasText(key)) {
            queryWrapper.eq("agent_id", key);
        }
        IPage<PaymentEntity> data = paymentService.page(new Page<>(page, limit), queryWrapper);
        return R.ok(data);
    }

    /**
     * 计算薪酬
     *
     * @return
     */
    @GetMapping("/admin/payment/cal")
    public R calPayment() {
        String lastMonth = SystemUtil.getLastMonth();
        Date lastMonthDate = SystemUtil.getLastMonthDate();
        QueryWrapper<AgentEntity> agentEntityQueryWrapper = new QueryWrapper<>();
        agentEntityQueryWrapper.gt("contract_period", lastMonthDate);
        List<AgentEntity> agentEntities = agentService.list(agentEntityQueryWrapper);
        for (AgentEntity agentEntity : agentEntities) {
            QueryWrapper<PerformanceEntity> performanceQueryWrapper = new QueryWrapper<>();
            performanceQueryWrapper.eq("agent_id", agentEntity.getId());
            performanceQueryWrapper.eq("time", lastMonth);
            PerformanceEntity performanceEntity = performanceService.getOne(performanceQueryWrapper);
            BigDecimal basicAmount = agentEntity.getBasic().multiply(BigDecimal.valueOf(performanceEntity.getAttendanceDays()));
            BigDecimal performanceAmount;
            if (performanceEntity.getAttendanceDays() > 20) {
                performanceAmount = agentEntity.getPerformanceAmount().multiply(performanceEntity.getTotalScore());
            } else {
                performanceAmount = BigDecimal.ZERO;
            }
            BigDecimal realAmount = basicAmount.add(performanceAmount);

            QueryWrapper<PaymentEntity> paymentQueryWrapper = new QueryWrapper<>();
            paymentQueryWrapper.eq("agent_id", agentEntity.getId());
            paymentQueryWrapper.eq("time", lastMonth);
            PaymentEntity paymentEntity = paymentService.getOne(paymentQueryWrapper);
            if (paymentEntity == null) {
                paymentEntity = new PaymentEntity();
                paymentEntity.setAgentId(agentEntity.getId());
                paymentEntity.setAgentName(agentEntity.getName());
                paymentEntity.setTime(lastMonth);
                paymentEntity.setBasic(basicAmount);
                paymentEntity.setPerformance(performanceAmount);
                paymentEntity.setRealAmount(realAmount);
                paymentService.save(paymentEntity);
            } else {
                paymentEntity.setBasic(basicAmount);
                paymentEntity.setPerformance(performanceAmount);
                paymentEntity.setRealAmount(realAmount);
                paymentService.updateById(paymentEntity);
            }
        }
        return R.ok();
    }
}
